package com.xing.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if ("user".equals(beanName)) {
			System.out.println("postProcessBeforeInitialization()->user对象初始化方法前开始增强...");
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if ("user".equals(beanName)) {
			System.out.println("postProcessAfterInitialization()->user对象初始化方法后开始增强...");
			//cglib代理对象
			Enhancer enhancer = new Enhancer();
			enhancer.setSuperclass(bean.getClass());
			enhancer.setCallback(new InvocationHandler() {
				@Override
				public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
					return method.invoke(method,objects);
				}
			});
			return enhancer.create();

		}
		return bean;
	}
}
